import mongoose from 'mongoose';
import db from './db';
mongoose.Promise = global.Promise;

const CourseSchema = new mongoose.Schema({
    courseName: String,
    teacher: String,
    tags: Object,
    cmtNumber: Number,
    // msg: Array,
    score: Array,
    likes: Object,
    creator: {
        type: Object,
        default: {},
    },
    schoolId: String
});

CourseSchema.methods.saveCourse = function (course, cb) {
    this.model('course').insertMany([course], cb);
};

CourseSchema.methods.getCourses = function (query, cb) {
    const { current = 1, pageSize = 10, ...leftQuery } = query;
    const courseModel = this.model('course');
    courseModel.count(leftQuery, function (err, count) {
        courseModel.find(leftQuery).skip((current - 1) * pageSize).limit(pageSize).exec((err, courses) => cb(err, courses, count));
    });
};

CourseSchema.methods.getAllCourses = function (query, cb) {
    this.model('course').find(query, { name: 1, _id: 0 }, cb);
};

CourseSchema.methods.getCourse = function (query, cb) {
    this.model('course').findOne(query, cb);
};

CourseSchema.methods.updateCourse = function (course, cb) {
    const _id = course._id;
    delete course._id;
    this.model('course').findOneAndUpdate({ _id }, { $set: course }, cb);
};

CourseSchema.methods.removeCourses = function (courseIds, cb) {
    this.model('course').remove({ _id: { $in: courseIds } }, cb);
};

export default db.model('course', CourseSchema);